package cn.qu.dockman.mgr.disparte;

import cn.qu.dockman.mgr.entity.Env;
import cn.qu.dockman.mgr.entity.Host;
import cn.qu.dockman.mgr.resp.EnvBean;
import cn.qu.dockman.mgr.service.EnvService;
import cn.qu.dockman.mgr.service.HostService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by zh on 17/3/21.
 */
public class RegisterObserver implements Observer {

    private static final Logger logger = LoggerFactory.getLogger(RegisterObserver.class);

    @Autowired
    private HostService hostService;

    @Autowired
    private EnvService envService;

    public RegisterObserver(DispartMgr dispartMgr) {
        dispartMgr.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {

        if (arg instanceof ArgDef) {
            ArgDef def = (ArgDef) arg;
            switch (def.getName()) {
                case "register": {
                    String token = (String) def.getData();
                    Host host = hostService.findByIp(def.getHost());
                    if (StringUtils.isBlank(token)) {
                        logger.error("未找到token");
                    } else {
                        if (host == null) {
                            List<EnvBean> envList = envService.findEnvs();
                            int envId = -1;
                            for (EnvBean bean : envList) {
                                String envCode = bean.getEnv().getEnvCode();
                                String md5 = DigestUtils.md5Hex(envCode);
                                if (envId > 0) continue;
                                if (StringUtils.equalsIgnoreCase(md5, token)) {
                                    envId = bean.getEnv().getId();
                                }
                            }

                            host = new Host();
                            host.setEnvId(envId);
                            host.setHostStatus(0);
                            host.setHostIp(def.getHost());
                            host.setHostMem(0);
                            host.setHostMemUsed(0);
                            host.setHostCpu(0);
                            host.setHostCpuUsed(0);
                            host.setHostDisk(0);
                            host.setHostDiskUsed(0);
                            host.setHostName(def.getHostname());
                            hostService.insertHost(host);
                        }
                    }
                }
                break;
            }
        }
    }
}
